/*
 * @Description:
 * @Author: 小雨
 * @Date: 2024-07-02 15:39:07
 * @LastEditTime: 2024-07-04 17:27:21
 * @LastEditors: 小雨
 */
const express = require('express');
const jsonwebtoken = require('jsonwebtoken');
const expressJwt = require('express-jwt');
const cors = require('cors');
const userRouter = require('./router/user');
const userinfoRouter = require('./router/userinfo');
const joi = require('joi');
const config = require('./config');

const app = express();

//解决跨域
app.use(cors());

//解决客户端传来application/x-www-form-urlencoded格式数据
app.use(express.urlencoded({ extended: false }));

//在路由之前封装自定义发送消息中间件
app.use((req, res, next) => {
    res.cc = function (err, status = 1) {
        res.send({
            status,
            msg: err instanceof Error ? err.message : err,
        });
    };
    next();
});

//在路由之前配置解析token中间件
app.use(expressJwt.expressjwt({ secret: config.jwtSecretKey, algorithms: ['HS256'] }).unless({ path: [/^\/api/] }));

//使用路由模块
app.use('/api', userRouter);
app.use('/my', userinfoRouter);

//定义错误级别中间件
app.use((err, req, res, next) => {
    //注册验证失败导致错误
    if (err instanceof joi.ValidationError) {
        return res.cc(err);
    }
    //捕获tokenjwt解析失败后产生的错误
    if (err.name === 'UnauthorizedError') return res.cc('身份认证失败');
    res.cc(err);
});

app.listen(80, () => {
    console.log('服务器启动');
});
